set more off

use dataset, clear

*** covariates ***

local X1 totalrevownsourcespcp pcttotaltax pcttotalig
local X2 lpopulation popdensity incomepcp pctba pct65plus H pcthisp herf pctforeign
local X3 crimepcp totalpolicepcp dem ngovspcp netmigration 

local X `X1' `X2' `X3'

keep if year == 2012

foreach x in `X' pctblack {
	su `x'
	replace `x' = (`x' - r(min)) / (r(max) - r(min))
}


eststo clear

set matsize 10000
 
 
eststo, title("Baseline"): reg lfinesandforfeitspcp pctblack `X1' `X2' `X3', robust
//eststo, title("Instrumental Variables"): ivreg lfinesandforfeitspcp (pctblack = pctblack1980) `X', robust 
eststo, title("State Fixed Effects"): areg lfinesandforfeitspcp pctblack `X', robust a(fipsst)
egen cid = group(fipsco fipsst)
eststo, title("County Fixed Effects"): areg lfinesandforfeitspcp pctblack `X', robust cl(cid) a(cid)
eststo, title("County-Clustered Standard Errors"): reg lfinesandforfeitspcp pctblack `X', robust cl(cid)
eststo, title("Population Under 10,000"): reg lfinesandforfeitspcp pctblack `X' if population2010 <= 10000, robust
eststo, title("Population Over 10,000"): reg lfinesandforfeitspcp pctblack `X' if population2010 >= 10000, robust 
//eststo, title("Add Alt. Measures of Diversity"): reg lfinesandforfeitspcp pctblack `X'  herf lH lpcthispanic lpctforeign , robust 

replace lfinesandforfeitspcp  = . if lfinesandforfeitspcp  == 0
gen anyfines = !mi(lfinesand)
eststo, title("Selection Model"): heckman lfinesandforfeitspcp pctblack `X', select(anyfines = pctblack `X') 

esttab, se nostar keep(pctblack) mtitles onecell unstack equation(1)


local myK = `r(nmodels)'
forvalues k = 1(1)`myK' {
	local mylab`k' = "(`k') " + r(m`k'_estimates_title)

}

matrix D = r(coefs)
matrix C = D[1, 1...]

eststo clear
local rnames : rownames C
local models : coleq C
local models : list uniq models
local i 0
foreach name of local rnames {
    local ++i
    local j 0
    capture matrix drop b
    capture matrix drop se
    foreach model of local models {
        local ++j
        matrix tmp = C[`i', 2*`j'-1]
        if tmp[1,1]<. {
            matrix colnames tmp = `model'
            matrix b = nullmat(b), tmp
            matrix tmp[1,1] = C[`i', 2*`j']
            matrix se = nullmat(se), tmp
        }
    }
    ereturn post b
    quietly estadd matrix se
    eststo `name'
}


#delimit;

esttab 
	using "tableA2.tex"
	,
		replace
		coeflabels(
			est1 "`mylab1'"
			est2 "`mylab2'"
			est3 "`mylab3'"
			est4 "`mylab4'"
			est5 "`mylab5'"
			est6 "`mylab6'"
			est7 "`mylab7'"
			est8 "`mylab8'"
			est9 "`mylab9'"
			est10 "`mylab10'"
			est11 "`mylab11'"
			est12 "`mylab12'"
		)
		noobs
		booktabs
		nonote
		cells(b(fmt(2) star) se(par))
		//onecell
		//incelldelimiter("&")
		gap
		nomtitles
		nonum
		unstack
		
		b(2)
		mlabels("Estimate")
		collabels("(s.e.)")
		align(c)
		width(\hsize)
		;

#delimit cr
